/*
 * This api js IS NOT the apicloud api.js, DO NOT mess up!!!
 * Promisify the apicloud API ajax function, nice to use
 */
import { sign, storage, router } from "./utils";
let statusMap = {
  501: "服务器异常,请稍后再试!",
  499: "服务器错误,请联系管理员!",
  401: res => {
    // api.alert({
    //     title: "提示",
    //     msg: res.reason || "登录已失效,请重新登录!",
    // }, function (ret, err) {
    //     storage.del('token');
    //     router.replace("./login");
    // });
    window.MuseUIMessage.close();
    window.MuseUIMessage.alert(res.reason || "登录已失效,请重新登录!", {
      type: "error",
      okLabel: "确认"
    }).then(({ result }) => {
      if (result) {
        storage.del("token");
        router.replace("./payLogin");
      }
    });
  }
};
function ajax({
  method = "get",
  hostType = "host1",
  url,
  headers,
  data,
  report = false
}) {
  let appVersion = api.appVersion.replace(/[\.\?]/g, "") * 1; //转换为整型
  data = {
    ...data,
    imei: api.deviceId,
    system: api.systemType,
    connection: api.connectionType,
    deviceType: api.deviceModel,
    version: appVersion,
    time: +new Date()
  };
  headers = headers ? headers : {};
  headers["Api-Key"] = storage.get("token");

  if (hostType === "host1") {
    if (api.pageType === "web") {
      url = `/oasis/${url}`;
    } else {
      url = `http://services.oasis-xd.com/oasis/${url}`;
      // url = `http://oasis.natapp1.cc/oasis/${url}`;
    }
  } else if (hostType === "host2") {
    url = `http://trade.oasis-xd.com/index/${url}`;
    // url = `http://oasis.free.idcfengye.com/index/${url}`;
  }
  console.log(`ajax=>${method}-${url}:${JSON.stringify(data)}`);
  return new Promise((resolve, reject) => {
    let old = JSON.parse(JSON.stringify(data));
    if (method == "file") {
      delete data.file;
    }
    sign(data).then(res => {
      try {
        window.MuseUIProgress.start();
        // 图片上传
        if (method == "file") {
          method = "post";
          data = {
            files: { file: old.file },
            values: {
              ...data,
              sign: res.value
            }
          };
        } else {
          data = { values: { ...data, sign: res.value } };
        }
        api.ajax({ url, method, headers, data, report }, (ret, err) => {
          ret = ret ? ret : {};
          window.MuseUIProgress.done();
          if (err || ret.status !== 200) {
            err = err ? err : {};
            checkError({
              status: err.status || ret.status,
              err: err.status ? err : ret
            });
            reject(err.status ? err : ret);
          } else {
            resolve(ret);
          }
        });
      } catch (error) {
        checkError({
          status: 499,
          err: error
        });
        reject(error);
      }
    });
  });
}
/**
 * @description 验证错误状态
 * @author 一枚前端
 */
function checkError({ status = 500, err, callback }) {
  console.log(status + "--" + JSON.stringify(err));
  try {
    if (status === 401) {
      statusMap[status](err); //执行退出登录操作
    } else {
      let msg =
        statusMap[status] ||
        (err.message || err.msg || err.reason || "网络响应超时,请稍后再试!");
      api.toast({
        msg: msg,
        duration: 2000,
        location: "bottom"
      });
      console.error(msg || JSON.stringify(err));
    }
  } catch (error) {
    console.error(error);
  }
}
export const $ajax = {
  get: param => {
    return ajax({ ...param, method: "get" });
  },
  post: param => {
    return ajax({ ...param, method: "post" });
  },
  file: param => {
    return ajax({ ...param, method: "file" });
  },
  put: param => {
    return ajax({ ...param, method: "put" });
  },
  delete: param => {
    return ajax({ ...param, method: "delete" });
  }
};
